package com.itheima.protocol.javaApi;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;


/**
 * 连接状态
 * KeeperState.Unknown;
 * KeeperState.Disconnected;
 * KeeperState.NoSyncConnected;
 * KeeperState.SyncConnected;
 * KeeperState.AuthFailed;
 * return KeeperState.ConnectedReadOnly;
 * return KeeperState.SaslAuthenticated;
 * return KeeperState.Expired;
 */
public class CreateNodeDemo implements Watcher {

    private final static String CONNECTIONSTRING = "192.168.1.108:2181";
    private final static int SESSIONTIMEOUT = 5000;
    private static CountDownLatch countDownLatch = new CountDownLatch(1);

    private static ZooKeeper zooKeeper;
    private static Stat stat = new Stat();

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {

        zooKeeper = new ZooKeeper(CONNECTIONSTRING, SESSIONTIMEOUT, new CreateNodeDemo());
        countDownLatch.await();
        System.out.println(zooKeeper.getState());

        //创建临时节点，临时节点先不能创建子节点
        String result = zooKeeper.create("/mic1", "123".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        zooKeeper.getData("/mic1", new CreateNodeDemo(), stat);
        System.out.println("创建成功：" + result);

        //更新节点1
        zooKeeper.setData("/mic1", "mic123".getBytes(), -1);
        Thread.sleep(2000);

        //更新节点2
        zooKeeper.setData("/mic1", "mic123456".getBytes(), -1);
        Thread.sleep(2000);

        //节点的删除
        /*zooKeeper.delete("/zk-book",-1);
        Thread.sleep(2000);*/

        //创建节点和子节点
        String path = "/node222";
        Stat stat2 = zooKeeper.exists(path, true);
        if(stat2 == null){
            zooKeeper.create(path,"123".getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
            TimeUnit.SECONDS.sleep(1);
        }

        //判断节点是否存在，来创建监听
        Stat stat = zooKeeper.exists(path + "/node1", true);
        if(stat == null){
            zooKeeper.create(path+"/node1","123".getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
            TimeUnit.SECONDS.sleep(1);
        }else {

            //修改子节点
            zooKeeper.setData(path+"/node1", "mic123456".getBytes(), -1);
            Thread.sleep(2000);

            //获取指定节点下的子节点
            List<String> nodes = zooKeeper.getChildren(path , true);
            System.out.println(nodes);

            //子节点删除
            zooKeeper.delete(path+"/node1",-1);
            TimeUnit.SECONDS.sleep(1);
        }
    }


    @Override
    public void process(WatchedEvent watchedEvent) {

        if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {

            //Event.EventType.None --> 连接状态
            if (Event.EventType.None == watchedEvent.getType() && null == watchedEvent.getPath()) {

                countDownLatch.countDown();
                System.out.println(watchedEvent.getState());

            } else if (watchedEvent.getType() == Event.EventType.NodeDataChanged) {

                try {
                    System.out.println("数据变更触发路径：" + watchedEvent.getPath() + "--> 改变后的值" +
                            zooKeeper.getData(watchedEvent.getPath(), true, stat));
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                //子节点数据变更会触发
            } else if (watchedEvent.getType() == Event.EventType.NodeChildrenChanged) {

                try {
                    System.out.println("子节点数据变更触发路径:" + watchedEvent.getPath() + "--> 子节点的值：" +
                            zooKeeper.getData(watchedEvent.getPath(), true, stat));
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                //创建子节点会触发
            } else if (watchedEvent.getType() == Event.EventType.NodeCreated) {

                try {
                    System.out.println("创建节点路径:" + watchedEvent.getPath() + "--> 节点的值：" +
                            zooKeeper.getData(watchedEvent.getPath(), true, stat));
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                //子节点删除会触发
            } else if (watchedEvent.getType() == Event.EventType.NodeDeleted) {

                System.out.println("删除节点路径: "+ watchedEvent.getPath());
            }
            System.out.println(watchedEvent.getType());
        }
    }
}
